<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>使用服务的形式改写请求</title>
		<script src="../angular.js"></script>

	</head>

	<body ng-app="MyApp">
		<div ng-controller="UserController">
			<ul>
				<li ng-repeat="name in dataList">
					{{name.Name}}
				</li>
			</ul>
		</div>
	</body>
	<script type="text/javascript">
		var app = angular.module("MyApp", []);
		app.controller("UserController", function($scope, UserService) {
			var promise = UserService.getList();
			promise.then(function(data) {
				$scope.dataList = data.sites; //调用承诺接口resolove()
			}, function(data) {
				$scope.dataList = "error:数据不存在..." //调用承诺结果reject()
			});
		});
		//注册服务
		app.factory("UserService", function($http, $q) {
			var serviceInstance = {
				getList: function() {
					var defer = $q.defer(); //声明延后执行
					$http({
						method: 'GET',
						url: 'home.json'
					}).
					success(function(data, status, headers, config) {
						defer.resolve(data);
					}).
					error(function(data, status, headers, config) {
						defer.reject();
					});
					return defer.promise; //返回承诺，返回获取数据的API
				}
			};
			// 我们的第一个服务
			return serviceInstance;
		})
	</script>

</html>